package action.common;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.aspectj.util.FileUtil;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;

import service.PlanService;
import action.vo.FileInfo;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = 1L;

    private HttpServletRequest request;

    private PlanService planService;

    private String planId;
    
    private String type;

    private List<FileInfo> processRequest(HttpServletRequest request, String filePath) throws IOException {

        if (!(request instanceof MultiPartRequestWrapper)) {
            return null;
        }
        List<FileInfo> fileInfoList = new ArrayList<FileInfo>();

        request.setCharacterEncoding("UTF-8");

        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
        Enumeration<String> fieldNames = multiWrapper.getFileParameterNames();
        while (fieldNames != null && fieldNames.hasMoreElements()) {
            String fieldName = fieldNames.nextElement();
            File[] files = multiWrapper.getFiles(fieldName);
            String[] names = multiWrapper.getFileNames(fieldName);
            for (int i = 0; i < files.length; i++) {
                String newName = createFileName(FilenameUtils.getExtension(names[i]));
                File target = new File(filePath + newName);
                FileUtil.copyFile(files[i], target);
                FileInfo info = new FileInfo();
                info.setName(names[i]);
                info.setUrl(newName);
                fileInfoList.add(info);
            }
        }
        return fileInfoList;
    }

    public String loadUserName() throws Exception {
        SecurityContext ctx = SecurityContextHolder.getContext();
        @SuppressWarnings("unused")
        String subPath = ctx.getAuthentication().getName();

        return SUCCESS;
    }

    public String uploadDxtp() throws Exception {

        String subPath = DigestUtils.shaHex(planId);
        String filePath = request.getSession().getServletContext().getRealPath("planFile\\dxtp\\" + subPath) + "\\";

        try {
            processRequest(request, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }
    
    public String uploadFafj() throws Exception {

        String subPath = DigestUtils.shaHex(planId);
        String filePath = request.getSession().getServletContext().getRealPath("planFile\\fafj\\" + subPath) + "\\";
        List<FileInfo> fileInfoList = null;
        try {
            fileInfoList = processRequest(request, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String path = getUrl(request).concat("/planFile/fafj/").concat(subPath).concat("/");
        if (fileInfoList != null) {
            for (FileInfo info : fileInfoList) {
                String url = path.concat(info.getUrl());
                planService.saveFafj(new Integer(planId), type, url, info.getName());
            }
        }

        return SUCCESS;
    }

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setPlanId(String planId) {
        this.planId = planId;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setPlanService(PlanService planService) {
        this.planService = planService;
    }

    private synchronized String createFileName(String extension) {
        Date dt = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = DigestUtils.shaHex(sdf.format(dt)).concat(".").concat(extension);
        return fileName;
    }

    private String getUrl(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getContextPath()).append("/");
        return sb.toString();
    }
}
